(function (doc) {
  class WaterFall {
    column = 5; //每行多少列
    leftGap = 10; //左空隙
    topGap = 10; //上空隙
    width;
    height;
    percent = 1;
    constructor(wrapperClass, column, leftGap, topGap) {
      this.column = column || this.column;
      this.leftGap = leftGap || this.leftGap;
      this.topGap = topGap || this.topGap;
      this.renderWaterFall(wrapperClass);
      window.addEventListener(
        "resize",
        this.debounce(() => {
          this.percent = this.width / this.height;
          console.log(this.percent);
          this.renderWaterFall(wrapperClass);
        })
      );
    }

    findMinIndexOfArray(arr) {
      const min = Math.min.apply(null, arr);
      return Array.prototype.indexOf.call(arr, min);
    }

    debounce(fn, delay = 1000) {
      let timer = null;
      const context = this;
      return function () {
        if (timer) return;
        timer = setTimeout(() => {
          fn.apply(context, arguments);
          clearTimeout(timer);
          timer = null;
        }, delay);
      };
    }

    calcScreenSize() {
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }

    renderWaterFall(parentNodeClass) {
      this.calcScreenSize();
      //获取容器下的所有需要放在瀑布流中的item
      const parentNode = doc.querySelector(parentNodeClass);
      const childrenNode = parentNode.children;
      //获取屏幕的也可以是你容器的宽高，这里占满屏幕所以用的屏幕的宽高
      //每一个item的宽度！
      const clientWidth =
        (this.width - this.leftGap * (this.column - 1)) / this.column;
      //用来存储每次图片放入容器后，当前容器里面每一个column中的高度，我们选取空间最大，对应高度最小的
      const heightSpaceArray = [];

      //循环遍历所有的元素
      for (let i = 0; i < childrenNode.length; i++) {
        childrenNode[i].style.width = `${clientWidth}px`;

        //关于第一个column和其他column的区别
        if ((i + 1) % this.column == 1) {
          //每一行的第一个left为0
          childrenNode[i].style.left = "0px";
        } else {
          //其他的根据当前的i去算left位置
          childrenNode[i].style.left = (clientWidth + this.leftGap) * i + "px";
        }

        //关于第一行和其他行的区别
        if (i < this.column) {
          //如果在第一行的：top 0
          childrenNode[i].style.top = "0px";
          //拿到最初始的空间高度的数组！
          heightSpaceArray.push(childrenNode[i].offsetHeight);
        } else {
          //从空间数组中找到上一行中最小的，也就是剩余空间最大的
          const minIndex = this.findMinIndexOfArray(heightSpaceArray);

          childrenNode[i].style.left =
            (this.leftGap + clientWidth) * minIndex + "px";

          childrenNode[i].style.top =
            heightSpaceArray[minIndex] + this.topGap + "px";

          //剩余空间最大的被放入元素后，要加入空隙以及被加入元素的高度！
          heightSpaceArray[minIndex] +=
            childrenNode[i].offsetHeight + this.topGap;
        }
      }
    }
  }

  window.onload = function () {
    const waterFall = new WaterFall(".wrapper");
  };
})(document);
